package org.hugh.trade.queue;

import org.hugh.trade.model.EntrustOrder;

import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.PriorityBlockingQueue;

public class OrderQueues {
    // PriorityBlockingQueue 是线程安全的
    /**
     * 买单队列 按价格降序排列，相同价格时间优先
     */
    private static final Map<String, PriorityBlockingQueue<EntrustOrder>> BUY_ORDER_QUEUES = new ConcurrentHashMap<>();
    /**
     * 卖单队列 按价格升序排列，相同价格时间优先
     */
    private static final Map<String, PriorityBlockingQueue<EntrustOrder>> SELL_ORDER_QUEUES = new ConcurrentHashMap<>();

    public static void addBuy(EntrustOrder order) {
        BUY_ORDER_QUEUES.putIfAbsent(order.getSecCode(), new PriorityBlockingQueue<>(
                16, Comparator.comparing(EntrustOrder::getPrice).reversed()
                .thenComparing(EntrustOrder::getTimestamp)
        ));
        BUY_ORDER_QUEUES.get(order.getSecCode()).add(order);
    }

    public static void addSell(EntrustOrder order) {
        SELL_ORDER_QUEUES.putIfAbsent(order.getSecCode(), new PriorityBlockingQueue<>(
                16, Comparator.comparing(EntrustOrder::getPrice)
                .thenComparing(EntrustOrder::getTimestamp)
        ));
        SELL_ORDER_QUEUES.get(order.getSecCode()).add(order);
    }

    static PriorityBlockingQueue<EntrustOrder> getBuyOrder(String secCode) {
        return BUY_ORDER_QUEUES.get(secCode);
    }

    static PriorityBlockingQueue<EntrustOrder> getSellOrder(String secCode) {
        return SELL_ORDER_QUEUES.get(secCode);
    }

}
